import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy.orm import Session
from datetime import datetime, timedelta
import random
import json
from database import get_db
from models import FlightLog, ExceptionLog, DetectionLog, Drone, Task, User, DetectionTarget, DetectionModel


def create_test_data(db: Session):
    """创建测试数据"""
    print("开始添加测试日志数据...")
    
    # 检查是否有无人机数据，如果没有则创建一些
    drones = db.query(Drone).all()
    if not drones:
        print("需要先创建无人机数据，正在创建...")
        for i in range(3):
            drone = Drone(
                drone_name=f"测试无人机{i+1}",
                drone_type_id=1,
                department_id=1,
                drone_code=f"DRONE-{i+1:03d}",
                status="1"
            )
            db.add(drone)
        db.commit()
        drones = db.query(Drone).all()
    
    # 检查是否有任务数据，如果没有则创建一些
    tasks = db.query(Task).all()
    if not tasks:
        print("需要先创建任务数据，正在创建...")
        for i in range(2):
            task = Task(
                name=f"测试任务{i+1}",
                description=f"测试任务描述{i+1}",
                status="completed",
                created_by=1
            )
            db.add(task)
        db.commit()
        tasks = db.query(Task).all()
    
    # 获取用户ID 1作为默认用户
    user = db.query(User).filter(User.id == 1).first()
    if not user:
        print("需要先创建用户数据，正在创建...")
        user = User(
            username="admin",
            password="$2b$12$testpasswordhash123456789012345",
            full_name="管理员",
            email="admin@example.com",
            status="1"
        )
        db.add(user)
        db.commit()
    
    # 添加飞行日志测试数据
    print("添加飞行日志测试数据...")
    for i in range(5):
        flight_log = FlightLog(
            drone_id=random.choice(drones).id,
            task_id=random.choice(tasks).id if tasks else None,
            record_time=datetime.now() - timedelta(minutes=i*30),
            latitude=39.9 + random.random() * 0.1,
            longitude=116.3 + random.random() * 0.1,
            altitude=100 + random.random() * 50,
            speed=5 + random.random() * 10,
            heading=random.random() * 360,
            roll=random.random() * 10 - 5,
            pitch=random.random() * 10 - 5,
            yaw=random.random() * 10 - 5,
            motor_speed_1=3000 + random.random() * 1000,
            motor_speed_2=3000 + random.random() * 1000,
            motor_speed_3=3000 + random.random() * 1000,
            motor_speed_4=3000 + random.random() * 1000,
            battery_voltage=24 + random.random() * 2,
            battery_current=10 + random.random() * 5,
            battery_percentage=80 - i * 10,
            temperature=30 + random.random() * 5,
            humidity=50 + random.random() * 20,
            wind_speed=2 + random.random() * 3,
            wind_direction=random.random() * 360,
            cpu_temperature=60 + random.random() * 10,
            gpu_temperature=65 + random.random() * 10,
            ram_usage=40 + random.random() * 20,
            task_progress=20 * i,
            current_waypoint_index=i,
            flight_mode="auto",
            gps_satellites=15 + random.randint(0, 10),
            gps_accuracy=2 + random.random() * 3,
            extended_data={"signal_strength": 85 + random.random() * 15}
        )
        db.add(flight_log)
    db.commit()
    
    # 获取刚创建的飞行日志
    flight_logs = db.query(FlightLog).order_by(FlightLog.id.desc()).limit(5).all()
    
    # 添加检测日志测试数据
    print("添加检测日志测试数据...")
    detection_targets = db.query(DetectionTarget).all()
    detection_models = db.query(DetectionModel).all()
    
    for i in range(8):
        detection_log = DetectionLog(
            drone_id=random.choice(drones).id,
            task_id=random.choice(tasks).id if tasks else None,
            flight_log_id=random.choice(flight_logs).id if flight_logs else None,
            detection_target_id=detection_targets[0].id if detection_targets else None,
            detection_model_id=detection_models[0].id if detection_models else None,
            detection_time=datetime.now() - timedelta(minutes=i*15),
            photo_time=datetime.now() - timedelta(minutes=i*15 + 1),
            latitude=39.9 + random.random() * 0.1,
            longitude=116.3 + random.random() * 0.1,
            altitude=120 + random.random() * 30,
            confidence=80 + random.random() * 15,
            detection_result={
                "objects": [
                    {
                        "type": "person" if i % 2 == 0 else "vehicle",
                        "confidence": 85 + random.random() * 10,
                        "bbox": [0.2, 0.3, 0.4, 0.5]
                    }
                ]
            },
            is_positive=i % 3 != 0,
            photo_path=f"/photos/detection_{i+1}.jpg",
            photo_thumbnail_path=f"/photos/thumbnails/detection_{i+1}_thumb.jpg",
            photo_metadata={"resolution": "1920x1080", "size": 2048576},
            notes=f"测试检测日志{i+1}",
            processed=i % 4 != 0
        )
        db.add(detection_log)
    db.commit()
    
    # 获取刚创建的检测日志
    detection_logs = db.query(DetectionLog).order_by(DetectionLog.id.desc()).limit(8).all()
    
    # 添加异常日志测试数据
    print("添加异常日志测试数据...")
    exception_types = ["system_error", "device_failure", "task_interruption"]
    exception_levels = ["critical", "warning", "info"]
    
    for i in range(6):
        exception_log = ExceptionLog(
            exception_type=random.choice(exception_types),
            exception_level=random.choice(exception_levels),
            title=f"测试异常{i+1}: {['系统错误', '设备故障', '任务中断'][i % 3]}报告",
            description=f"这是一条测试异常日志描述，详细说明了异常{i+1}的情况。",
            drone_id=random.choice(drones).id,
            task_id=random.choice(tasks).id if tasks else None,
            detection_log_id=random.choice(detection_logs).id if detection_logs else None,
            location={
                "latitude": 39.9 + random.random() * 0.1,
                "longitude": 116.3 + random.random() * 0.1,
                "address": "测试地点"
            },
            responsible_user_id=user.id if user else None,
            status="resolved" if i % 2 == 0 else "pending",
            resolution_description=f"异常已解决，通过重启系统解决了问题。" if i % 2 == 0 else None,
            resolution_time=datetime.now() - timedelta(minutes=i*10) if i % 2 == 0 else None,
            created_at=datetime.now() - timedelta(hours=i),
            updated_at=datetime.now() - timedelta(hours=i) + timedelta(minutes=5)
        )
        db.add(exception_log)
    db.commit()
    
    print("测试日志数据添加完成！")
    print(f"- 飞行日志: {len(flight_logs)} 条")
    print(f"- 检测日志: {len(detection_logs)} 条")
    print(f"- 异常日志: 6 条")


def main():
    """主函数"""
    db = next(get_db())
    try:
        create_test_data(db)
    except Exception as e:
        print(f"添加测试数据时出错: {str(e)}")
        db.rollback()
    finally:
        db.close()


if __name__ == "__main__":
    main()